using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace GottaGottaScrum.Models
{ 
    public class WorkItemRepository : IWorkItemRepository
    {
        GottaGottaScrumContext context = new GottaGottaScrumContext();

        public IQueryable<WorkItem> All
        {
            get { return context.WorkItems; }
        }

        public IQueryable<WorkItem> AllIncluding(params Expression<Func<WorkItem, object>>[] includeProperties)
        {
            IQueryable<WorkItem> query = context.WorkItems;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public WorkItem Find(int id)
        {
            return context.WorkItems.Find(id);
        }

        public void InsertOrUpdate(WorkItem workitem)
        {
            if (workitem.Id == default(int)) {
                // New entity
                context.WorkItems.Add(workitem);
            } else {
                // Existing entity
                context.Entry(workitem).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var workitem = context.WorkItems.Find(id);
            context.WorkItems.Remove(workitem);
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }

    public interface IWorkItemRepository
    {
        IQueryable<WorkItem> All { get; }
        IQueryable<WorkItem> AllIncluding(params Expression<Func<WorkItem, object>>[] includeProperties);
        WorkItem Find(int id);
        void InsertOrUpdate(WorkItem workitem);
        void Delete(int id);
        void Save();
    }
}